<template>
  <div
    style="width: 100%; height: 100%"
    class="q-pa-sm column golden-layout-panel"
  >
    <q-scroll-area ref="scroller" class="q-pa-md col">
      <div style="width: 100%">
        <q-chat-message
          v-for="msg in messages"
          :avatar="msg.userAvatar"
          :key="msg.id"
          :name="msg.userName"
          :text="[msg.content]"
          :sent="msg.isSent"
          :stamp="msg.timeString"
        />
      </div>
    </q-scroll-area>
    <div>
      <q-input
        color="accent"
        rounded
        standout
        class="col"
        v-model="text"
        maxlength="60"
        :dense="true"
        :hide-bottom-space="true"
        @keydown.enter.prevent="sendMessage"
      >
        <template v-slot:append>
          <q-icon
            v-if="text !== ''"
            name="close"
            @click="text = ''"
            class="cursor-pointer"
          />
          <q-btn rounded flat fab-mini icon="mdi-emoticon">
            <emoji-panel @insert="onInsertEmoji" />
          </q-btn>
        </template>

        <template v-slot:after>
          <q-btn round dense flat icon="mdi-send-circle" @click="sendMessage" />
        </template>
      </q-input>
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent, ref, Ref, onUpdated, onBeforeUpdate } from 'vue';
import EmojiPanel from './EmojiPanel.vue';
import Message from 'src/models/ChatMessage';
import moment from 'moment';
export default defineComponent({
  name: 'chat-panel',
  components: {
    EmojiPanel,
  },
  setup() {
    let text = ref('');
    let messages: Ref<Message[]> = ref([]);
    const scroller: any = ref(null);
    onBeforeUpdate(() => {
      if (scroller.value && scroller.value !== null) {
        scroller.value.setScrollPercentage('vertical', 2);
      }
    });
    onUpdated(() => {
      if (scroller.value && scroller.value !== null) {
        scroller.value.setScrollPercentage('vertical', 2);
      }
    });
    return {
      text,
      messages,
      scroller,
      sendMessage() {
        let msg: Message = new Message();
        msg.id = moment().valueOf().toString();
        msg.createTime = moment().valueOf();
        msg.content = text.value;
        msg.userName = 'ME';
        msg.isSent = true;
        text.value = '';
        messages.value.push(msg);
      },
      onInsertEmoji(emoji: string) {
        text.value += emoji;
      },
    };
  },
});
</script>
